package com.mine.eureka.controllers;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消息生产者
 */
@Component
public  class MqProducer {

    static  private final Logger logger = LoggerFactory.getLogger(MqProducer.class);
    /**
     *  消息生产者
     */
    @Autowired
    private  DefaultMQProducer _mqProducer;


    /**
     *  发送消息
     *
     * @param topic 主题
     * @param msg 消息
     */
     public  SendResult sendMsg(String topic,Object msg) {
        if (null == topic || null == msg) {
            return null;
        }
        SendResult result = null;
        Message newMessage = new Message();
        newMessage.setTopic(topic);
        newMessage.setBody(JSONObject.toJSONBytes(msg));

        try {
            // 发送消息
             result = _mqProducer.send(newMessage);
            logger.info("信息发送成功");
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return result;
    }

}
